package com.hula.onion.book.server.spider.platforms.yuanbao365;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.CookieUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Description:元宝365
 * Create Date:2018/1/30 19:33
 *
 * @author liangbing
 * @version 1.0
 */
@Component("yuanBao365Spider")
public class YuanBao365Spider extends SpiderCommon {

    /**
     * 登录页面URL
     */
    private static final String LOGIN_PAGE_URL = "https://www.yuanbao365.com/user/login.html";

    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.yuanbao365.com/user/login.do";

    /**
     * 验证码URL
     */
    private static final String CAPTCHA_URL = "https://www.yuanbao365.com/captcha.svl";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.lljr.com/myAccount/myInvestment";

    @Autowired
    private YuanBao365SpiderHelper spiderHelper;

    /**
     * 执行爬取操作
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);
        //1. 从缓存中获取cookie，设置到cookie store中
        CookieUtils.setCookie(loginForm.getPlatformId(), loginForm.getUserId(), getHttpContext().getCookieStore());

        //模拟登陆
        String loginStr = HttpUtils.post(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm),
                getHttpContext());
        if (StringUtils.isEmpty(loginStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        logger.info("[YuanBao365Spider] Http response result:{}", loginStr);

        String status = JSONObject.parseObject(loginStr).getString("success");
        //登陆成功
        if ("yes".equals(status)) {
            return spiderHelper.parseAccountBalance(loginStr);
        } else {
            commonResponse = new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
            commonResponse.setMsg(JSONObject.parseObject(loginStr).getString("errormsg"));
            return commonResponse;
        }
    }

    @Override
    public String getCaptchaURL() {
        return CAPTCHA_URL;
    }

    @Override
    public String getLoginPageURL() {
        return LOGIN_PAGE_URL;
    }

}

